<template>
  <div class="app-container">
    <el-row :gutter="10">
        <el-col :span="11">
            <el-card class="box-card">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                    <el-form-item label="选择区域" prop="region">
                        <el-cascader
                          style="width: 130px;"
                          v-model="queryParams.region"
                          :options="regionOptionsAll"
                          :props="{ value:'label',label:'label'}"
                          clearable></el-cascader>
                    </el-form-item>
                    <el-form-item label="学校名称" prop="name">
                        <el-input
                          style="width: 140px;"
                          v-model="queryParams.name"
                          placeholder="请输入学校名称"
                          clearable
                          @keyup.enter.native="handleQuery"
                          />
                        <el-button type="primary" 
                          style="margin-left: 10px;"
                          size="mini" 
                          @click="handleQuery">搜索</el-button>
                    </el-form-item>
                   
                </el-form>
                <el-collapse v-if="schoolList.length > 0" style="margin-top: 20px;"
                  v-model="activeItem" accordion @change="handleExpand" >
                  <el-collapse-item 
                    v-for="item in schoolList"
                    :key="item.value"
                    :title="item.label"
                    :name="item.value">
                    <template slot="title">
                      <span class="school-text">{{ item.label }}</span>
                    </template>
                      <div class="class-container">
                        <div class="class-panel" v-loading="loading">
                          <ul v-if="classList.length > 0">
                            <li :class="{'active': item.value == selectedItem.value}"
                              @click="handleClickClass(item)"
                              v-for="item in classList"
                              :key="item.value">{{ item.label }}</li>
                          </ul>
                          <el-empty v-else :image-size="50" description="班级为空"></el-empty>
                        </div>
                        <div class="setting">
                          <el-dropdown @command="handleCommand">
                            <el-button 
                              type="primary" 
                              icon="el-icon-setting" plain circle></el-button>
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item command="1">新建</el-dropdown-item>
                              <!-- <el-dropdown-item 
                                command="2"
                                :disabled="selectedItem.value==undefined">编辑</el-dropdown-item> -->
                              <el-dropdown-item 
                                divided
                                command="3" 
                                :disabled="selectedItem.value==undefined">
                                <span style="color: #F56C6C">删除</span>
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </div>
                      </div>
                    </el-collapse-item>
                </el-collapse>
                <el-empty v-else :image-size="50" description="学校列表为空"></el-empty>
            </el-card>
        </el-col>
        <el-col :span="13">
          <studentsTable ref="studentsTable" :classItem="selectedItem" />
        </el-col>
    </el-row>
    <!-- 新建班级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="480px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="年级" prop="grade">
              <el-select style="width: 100%" v-model="form.grade" placeholder="选择年级" clearable>
                <el-option
                  v-for="dict in dict.type.sys_school_grade"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
         <el-col :span="22">
            <el-form-item label="班级" prop="classNameText">
              <el-input v-model="form.classNameText" placeholder="多个班级可用[,]分隔" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSchool } from "@/api/school/school.js";
import { listClassById, addClasses, delClass } from "@/api/school/class.js";
import { regionData, regionDataAllOption } from '@/config/region-shandong.js'
import studentsTable from "./components/students-table.vue"
export default {
  name: "StudentsList",
  dicts: ['sys_school_grade'],
  data() {
    var validateClassName = (rule, value, callback) => {
      if(value == '') {
        callback(new Error('请输入班级'));
      }
      else if (!/^\d+(,\d+)*$/.test(value)) {
        callback(new Error('只允许输入数字或“,”分隔的数字'));
      }
      else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      activeItem: undefined,
      // 总条数
      total: 0,
      //地域数组
      regionOptions: regionData,
      regionOptionsAll: regionDataAllOption,
      // 学校表格数据
      schoolList: [],
      // 班级表格数据
      classList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      /**选中的班级ID */
      selectedItem: {},
      // 查询参数
      queryParams: {
        region: ['青岛市', '全部'],
        name: undefined
      },
      // 表单参数
      form: {},
      eidtSchoolId: undefined,
      // 表单校验
      rules: {
        grade: [
          { required: true, message: "地域不能为空", trigger: "change" }
        ],
        classNameText: [
          { required: true, validator: validateClassName,  trigger: "change" }
        ]
      }
    };
  },
  components: {
    studentsTable
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学校列表 */
    getList() {
      let region = this.queryParams.region;
      // console.log(region)
      this.queryParams.province = '山东省';
      this.queryParams.city = region[0]||'';
      this.queryParams.district = (region[1]||'').replace('全部', '');
      console.log(this.queryParams)
      listSchool(this.queryParams).then(response => {
        this.schoolList = response.data;
      });
    },
    /**根据学校ID查询班级 */
    getClassesList(schoolId) {
      this.loading = true;
      listClassById({ schoolId }).then(res => {
        console.log(res)
        this.classList = res.data
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
     // 表单重置
    reset() {
      this.form = {
        id: undefined,
        schoolId: undefined,
        grade: undefined,
        classNameText: '',
        className: []
      };
      this.resetForm("form");
    },
    /* 展开行 */
    handleExpand(schoolId) {
      this.classList = []
      //如果展开数组行数大于1，表示展开行
      if(schoolId) {
        this.eidtSchoolId = schoolId
        //根据学校ID查询班级
        this.getClassesList(schoolId)
      }
    },
    /*创建班级*/
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.schoolId = this.eidtSchoolId
          this.form.className = this.form.classNameText.split(',')
          console.log(this.form)
          addClasses(this.form).then(res => {
            this.$modal.msgSuccess("创建成功");
            this.open = false;
            this.getClassesList(this.form.schoolId);
          })
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    /**班级操作 */
    handleCommand(flag) {
      // console.log(flag)
      switch (flag) {
        case '1':
          this.handleAdd();
          break;
        case '2':
          this.handleEdit();
          break;
        case '3':
          this.handleDelete();
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建班级";
    },
    /**编辑班级 */
    handleEdit() {
      this.reset();
      this.open = true;
      this.title = "编辑班级";
    },
    /**删除班级 */
    handleDelete() {
      const label = this.selectedItem.label
      const id = this.selectedItem.value
      this.$modal.confirm('是否确认删除班级"' + label + '"的数据项？').then(function() {
        return delClass({id});
      }).then(() => {
        this.getClassesList(this.eidtSchoolId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 根据班级查询学生列表 */
    handleClickClass(item) {
      this.selectedItem = item
      this.$refs['studentsTable'].handleInit(item);
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .box-card{
        min-height: calc(100vh - 120px);
    }
    .class-container{
      display: flex;
      .class-panel{
        flex: 1;
        margin: 0 40px;
        padding: 0 20px;
        max-height: 400px;
        overflow:auto;
        ul{
          border: 1px solid #7F9CF5;
          border-radius: 3px;
          padding: 0;
          li{
            list-style: none;
            height: 36px;
            text-align: center;
            line-height: 36px;
            border-bottom: 1px solid #A3BFFA;
            cursor: pointer;
            &:nth-last-child(1){
              border-bottom: none;
            }
            &.active{
              background: #A3BFFA;
              color: #fff;
            }
          }
        }
      }
    }
    .school-text{
      font-size: 16px!important;
    }
</style>
